<!--
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2022-12-02 18:59:00
 * @LastEditors: Andy
 * @LastEditTime: 2023-03-27 17:23:53
-->
<template>
  <x-dialog :title="title" :show.sync="visible" v-if="visible" :before-close="handleClose" width="40%">
    <el-form :model="params" class="demo-form-inline" ref="params" :rules="rules" label-position="top">
      <el-row :gutter="20">
        <el-col :span="12" v-if="params.parentId + '' !== '0'">
          <el-form-item :label="$t('organization.post.prePost')" prop="parentId">
            <x-select-tree v-model="params.parentId" :options="postTreeOptions" :defaultProps="defaultPostProps" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('organization.post.organizPost')" prop="deptId">
            <x-select-tree
              ref="selectTree"
              :placeholder="$t('system.user.pleaseSelect')"
              v-model="params.deptId"
              :options="deptOptions"
              :defaultProps="defaultDeptProps"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('organization.post.postName')" prop="postName">
            <el-input v-model="params.postName" :placeholder="$t('system.user.remarktxt')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('organization.post.postCode')" prop="postCode">
            <el-input v-model="params.postCode" :placeholder="$t('system.user.remarktxt')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('organization.post.postNick')" prop="shortName">
            <el-input v-model="params.shortName" :placeholder="$t('system.user.remarktxt')" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('organization.post.postRank')" prop="postRank">
            <x-select
              :placeholder="$t('system.user.pleaseSelect')"
              v-model="params.postRank"
              :options="dictOptions['upms_post.post_rank']"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('organization.post.showNumber')" prop="sort">
            <el-input-number size="small" v-model="params.sort" controls-position="right" :min="1"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('organization.post.toStart')" prop="state">
            <!-- <template #label>
              <span>
                <el-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                  <em class="el-icon-question" />
                </el-tooltip>
                {{$t('organization.post.showNumber')}}
              </span>
            </template> -->
            <x-radio-group :list-data="dictOptions['system.state']" v-model="params.state"></x-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('organization.post.allotRole')">
            <template #label>
              <em class="required-icon"> * </em>
              <span>{{ $t('organization.post.allotRole') }}</span>
            </template>
            <x-page-transfer
              ref="roleTransfer"
              :from-data="roleList"
              :to-data="params.roleIds"
              :title="[$t('organization.post.roleList'), $t('organization.post.checkRole')]"
              :attrOption="attrOption"
              :paginationData="pagination"
              @on-change="handleTableChange"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer">
      <el-button @click="handleClose"> {{ $t('common.cancel') }} </el-button>
      <el-button
        type="primary"
        @click="
          loading = true
          handleSubmit()
        "
        :loading="loading"
      >
        {{ $t('common.confirm') }}
      </el-button>
      <!-- <el-button v-if="params.parentId + '' === '0' && params?.id" type="danger" @click="handleDeletePost">
        {{ $t('common.delete') }}
      </el-button> -->
    </span>
  </x-dialog>
</template>
<script>
  import { cloneDeep, omit, throttle, TableListMixin } from '@package/utils'
  // import {  } from '@/common/mixins'
  import { apiPostAddPost, apiPutEditPost, apiPostDeptTree, apiGetPostInfo } from '../api'
  import { pageRoleUrl } from '../../auth/api'
  import { EnumApiCode } from '../../../../../../globalEnum.js'

  export default {
    mixins: [TableListMixin],
    props: {
      postTreeOptions: {
        type: Array,
        default: () => []
      },
      dictOptions: {
        type: Object,
        default: () => ({})
      },
      defaultPostProps: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        disableMixinCreated: true,
        pageRoleUrl,
        visible: false,
        loading: false,
        deptOptions: [],
        title: '',
        params: {
          parentId: '',
          deptId: '',
          postName: '',
          postCode: '',
          shortName: '',
          postRank: '',
          sort: 1,
          state: '1',
          roleIds: []
        },
        isParent: true,
        attrOption: {
          label: 'roleName',
          value: 'id'
        },
        defaultDeptProps: {
          label: 'deptName',
          value: 'id',
          children: 'children'
        },
        rules: {
          parentId: [{ required: true, message: this.$t('organization.post.prePostPlaceholder'), trigger: 'blur' }],
          deptId: [
            { required: true, message: this.$t('organization.post.deptPlaceholder'), trigger: ['blur', 'change'] }
          ],
          postRank: [{ required: true, message: this.$t('organization.post.levelPlaceholder'), trigger: 'blur' }],
          postName: [
            { required: true, message: this.$t('organization.post.namePlaceholder'), trigger: 'blur' },
            { min: 1, max: 30, message: this.$t('organization.post.lengthPlaceholder'), trigger: 'blur' }
          ],
          postCode: [
            { required: true, message: this.$t('organization.post.codePlaceholder'), trigger: 'blur' },
            { min: 1, max: 30, message: this.$t('organization.post.lengthPlaceholder'), trigger: 'blur' }
          ],
          shortName: [
            { required: true, message: this.$t('organization.post.shortNamePlaceHolder'), trigger: 'blur' },
            { min: 1, max: 30, message: this.$t('organization.post.lengthPlaceholder'), trigger: 'blur' }
          ],
          sort: [{ required: true, message: this.$t('organization.post.sortPlaceholder'), trigger: 'blur' }],
          state: [{ required: true, message: this.$t('organization.post.statePlaceholder'), trigger: 'blur' }],
          roleIds: [{ required: true, message: this.$t('organization.post.rolePlaceholder'), trigger: 'blur' }]
        }
      }
    },
    computed: {
      roleList() {
        return this.tableData || []
      },
      listUrl() {
        return this.pageRoleUrl
      }
    },
    created() {
      this.loadDeptTree()
      this.loadData()
    },
    methods: {
      handleOpen(info, isParent = true) {
        this.visible = true
        this.params.parentId = info.parentId
        this.params.deptId = info?.deptId ?? ''
        this.isParent = isParent
        if (info?.id) {
          this.title = this.$t('organization.post.editPost')
          this.$nextTick(() => {
            this.getPostInfo(info.id)
          })
          return
        }
        this.params = Object.assign(this.params, cloneDeep(info))
        this.title = this.$t('organization.post.addPost')
      },
      async getPostInfo(id) {
        const { data, code } = await apiGetPostInfo(id)
        if (code === EnumApiCode.Success) {
          this.params = cloneDeep(data)
          if (this.params?.roles) {
            this.params.roleIds = this.params.roles
          }
          this.params.state += ''
        }
      },
      async loadDeptTree() {
        const { data, code } = await apiPostDeptTree()
        if (code === EnumApiCode.Success) {
          this.deptOptions = data
        } else {
          this.$message.error(msg)
        }
      },
      handleSubmit: throttle(function () {
        this.loading = true
        this.$refs.params.validate(async (valid) => {
          if (valid) {
            if (!this.$refs.roleTransfer.modeOptions.length) {
              this.$message.error(this.$t('organization.post.rolePlaceholder'))
              return
            }
            const orgId = this.$refs.selectTree?.currentNode.orgId ?? this.params.orgId
            const param = {
              ...omit(this.params, 'roles'),
              orgId,
              roleIds: this.$refs.roleTransfer.modeOptions.map((v) => v[this.attrOption.value])
            }
            try {
              const { code, msg } = 'id' in this.params ? await apiPutEditPost(param) : await apiPostAddPost(param)
              this.loading = false
              if (code === EnumApiCode.Success) {
                this.$refs.params.resetFields()
                this.$message.success(this.$t('system.user.newSuccess'))
                this.$emit('handleSuccess')
                this.handleClose()
              } else {
                this.$message.error(msg)
              }
            } finally {
              this.loading = false
            }
          } else {
            this.loading = false
            return false
          }
        })
      }, 1000),
      handleClose() {
        this.$refs.params.resetFields()
        this.params.roleIds = []
        this.params = omit(this.params, 'id')
        this.visible = false
      },
      handleDeletePost() {
        this.$emit('on-delete', this.params.id)
        this.handleClose()
      }
    }
  }
</script>
<style lang="scss" scoped>
  .required-icon {
    margin-right: 4px;
    color: #f56c6c;
  }
</style>
